#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <thread>
#include <unistd.h>

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "./HttpServer port" << std::endl;
        exit(-1);
    }

    int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[1]));
    inet_aton("0.0.0.0", &server.sin_addr);
    if (bind(listen_sock, (sockaddr*)&server, sizeof server) < 0)
    {
        std::cerr << "bind error......." << std::endl;
        exit(1);
    }
    std::cout << "bind ok......" << std::endl;
    listen(listen_sock, 20);

    int sock;
    struct sockaddr_in client;
    socklen_t cilent_len = sizeof client;
    char buffer[1024];
    while (true)
    {
        sock = accept(listen_sock, (sockaddr*)&client, &cilent_len);
        if (sock < 0) continue;
        std::string client_ip = inet_ntoa(client.sin_addr);
        uint16_t client_port = ntohs(client.sin_port);
        std::cout << "[" << client_ip << ": " << client_port << "]这位小伙伴连接成功！" << std::endl;

        
        int n = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }

        std::string http_response = "HTTP/1.1 200 ok\r\n";
        http_response += "\r\n";
        http_response += "<html><h1>Hello World!</h1></html>";
        send(sock, http_response.c_str(), http_response.size(), 0);
        close(sock);
    }
    close(listen_sock);
    return 0;
}
